'use strict';

const Controller = require('egg').Controller;
class CategoryController extends Controller {
  async addCategory() {
    const { ctx } = this;
    try {
      ctx.validate({
        name: { type: 'string', required: true },
        img_url: { type: 'string', required: true },
        p_height: { type: 'string', required: true },
        icon_url: { type: 'string', required: true },
      }, ctx.request.body);
    } catch (err) {
      ctx.logger.error('addCategory err:', err);
      ctx.body = {
        code: -1,
        msg: '请求参数错误',
      };
      ctx.status = 400;
    }

    // 处理新增的逻辑
    const res = await this.service.category.addCategory(ctx.request.body);
    if (res.code === 0) {
      ctx.body = {
        code: 0,
        msg: '新增成功',
      };
    } else {
      ctx.body = {
        code: -1,
        msg: JSON.stringify(res) || '新增失败',
      };
    }
  }
  // 获取分类
  async getCategoryList() {
    const { ctx } = this;
    const res = await this.service.category.getCategoryList();
    if (res) {
      ctx.body = {
        code: 0,
        data: res,
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '获取商品分类失败',
      };
      ctx.status = 500;
    }
  }
  // 根据id获取分类
  async getCategoryById() {
    const { ctx } = this;
    const id = ctx.query.id;
    const res = await this.service.category.getCategoryById(id);
    if (res) {
      ctx.body = {
        code: 0,
        data: res,
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '获取商品分类信息失败',
      };
      ctx.status = 500;
    }
  }
  // 根据id更新分类
  async updateCategory() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await this.service.category.updateCategory(data);
    if (res.code === 0) {
      ctx.body = {
        code: 0,
        msg: '修改分类信息成功',
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '获取商品分类信息失败',
      };
      ctx.status = 500;
    }
  }

  // 删除分类
  async deleteCategory() {
    const { ctx } = this;
    const data = ctx.request.body;
    const res = await this.service.category.deleteCategory(data);
    if (res.code === 0) {
      ctx.body = {
        code: 0,
        msg: '删除分类成功',
      };
      ctx.status = 200;
    } else {
      ctx.body = {
        code: -1,
        msg: '删除分类失败',
      };
      ctx.status = 500;
    }
  }
}
module.exports = CategoryController;
